<template>
  <view class="container">
    <up-sticky :bgColor="isMove ? '#fff' : 'transparent'">
      <view class="tab_box">
        <up-tabs
          key=""
          lineWidth="40"
          :scrollable="false"
          :list="tabList"
          @click="changeTab"
          :activeStyle="{ color: '#FE7325' }"
          lineColor="#FE7325"
        ></up-tabs>
      </view>
      <view class="car_box" @click="openCarPop">
        <view class="car_in_box flex_sb">
          <view class="left flex_s">
            <view class="icon_box">
              <image src="@/static/image/car_icon.png" mode="scaleToFill" />
            </view>
            <template v-if="carListData.length">
              <text v-if="checkCar.license_plate">{{
                checkCar.license_plate
              }}</text>
              <text v-if="checkCar.vin">{{ checkCar.vin }}</text>
            </template>
            <text v-else> 尚未添加车辆信息 </text>
          </view>
          <view class="right">
            <up-icon name="arrow-down" color="#284968" size="14"></up-icon>
          </view>
        </view>
      </view>
    </up-sticky>

    <view class="list_box" v-if="dataList.length">
      <view
        class="list_item"
        v-for="(item, index) in dataList"
        :key="index"
        @click="goDetail(item)"
      >
        <voucherDetail :dataInfo="item">
          <view class="btm flex_sb">
            <view class="left_icon flex_s">
              <view class="icon_box">
                <image src="@/static/image/car_icon.png" mode="scaleToFill" />
              </view>
              <text v-if="item.vehicle.license_plate">{{
                item.vehicle.license_plate
              }}</text>
              <text v-if="item.vehicle.vin">{{ item.vehicle.vin }}</text>
              <up-icon name="arrow-right" color="#616161" size="14"></up-icon>
            </view>
            <view class="right_btn" v-if="item.status == 1"> 去使用 </view>
            <view class="right_btn used" v-else-if="item.status == 2">
              已核销
            </view>
            <view class="right_btn" v-else> 已失效 </view>
          </view>
        </voucherDetail>
      </view>
      <view class="loading_class flex_c" v-if="dataList.length > 0">
        <up-loading-icon v-if="loading"></up-loading-icon>
        {{ loadTitle }}
      </view>
    </view>
    <emptyPage v-else></emptyPage>
    <up-popup
      :show="carShow"
      mode="center"
      :safeAreaInsetBottom="false"
      round="20"
      @close="carShow = false"
    >
      <view class="car_class">
        <template v-if="carListData.length">
          <scroll-view
            scroll-y="true"
            :style="{ height: carListData.length > 2 ? '330rpx' : 'auto' }"
          >
            <view
              class="car_item flex_s"
              v-for="(item, index) in carListData"
              :key="index"
              @click="chooseCar(item)"
            >
              <view class="icon_box">
                <image src="@/static/image/car_icon.png" mode="scaleToFill" />
              </view>
              <view class="car_info">
                <view class="car_top">
                  <view class="car_id line1" v-if="item.license_plate">
                    {{ item.license_plate }}
                  </view>
                  <view class="car_id line1" v-if="item.vin">
                    {{ item.vin }}
                  </view>
                  <view class="car_name">
                    <text style="margin-right: 10rpx">{{ item.name }}</text
                    ><text>{{ item.phone }}</text>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </template>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import emptyPage from "@/components/emptyPage.vue";
import voucherDetail from "@/components/voucherDetail.vue";
import { JumpPath, Tips } from "@/utils";
import { reactive } from "vue";
import { onPageScroll, onReachBottom, onLoad, onShow } from "@dcloudio/uni-app";
import { voucherList, carList } from "@/api/car";
import { type CarItem, type VoucherItem } from "@/types/index";
onShow(() => {
  getCarList();
});
const carListData = ref<CarItem[]>([]);
const checkCar = ref<CarItem>({
  name: "",
  phone: "",
  id: 0,
  license_plate: "",
  vin: "",
});

function goDetail(item: VoucherItem) {
  if (item.status == 1) {
    JumpPath("/pages/detail/index?id=" + item.id);
  } else {
    Tips({ title: "该券" + tabList[tab_current.value].name });
  }
}

let carShow = ref<boolean>(false);

function openCarPop() {
  if (carListData.value.length > 1) {
    carShow.value = true;
  }
}
function chooseCar(info: CarItem) {
  checkCar.value = info;
  uni.setStorageSync("chooseCar", info);
  carShow.value = false;
}
// 说明：监听选中的汽车从而触发获取优惠券列表，优化用户从详情返回当前页面频繁触发请求
watch(
  () => checkCar.value,
  (nVal, oVal) => {
    console.log(nVal, oVal, "选中的汽车发生了变化重新请求优惠券");
    if (carListData.value.length > 0) {
      clearData();
      getData();
    }
  }
);

function getCarList() {
  carList().then((res: any) => {
    const data = res.data;
    carListData.value = data.list;
    const locaCar = uni.getStorageSync("chooseCar");
    if (locaCar) {
      let carInlist = carListData.value.find((item) => item.id == locaCar.id);
      if (carInlist) {
        // 防止频繁触发watch函数，当前的选择的汽车与本地存储的汽车id相同，则不执行watch函数
        if (checkCar.value.id == locaCar.id) return;
        checkCar.value = locaCar;
      } else {
        // 与上面同理（另：该判断是防止数据源被篡改，而前端本地存储未变的bug）
        uni.removeStorageSync("chooseCar");
        if (checkCar.value.id == carListData.value[0].id) return;
        checkCar.value = carListData.value[0];
      }
    } else {
      // 与上面同理
      if (checkCar.value.id == carListData.value[0].id) return;
      checkCar.value = carListData.value[0];
    }
  });
}
const dataList = ref<VoucherItem[]>([]);

const limit = ref(10);
const loadTitle = ref("加载更多");
const loadend = ref(false);
const loading = ref(false);
const page = ref(1);
function clearData() {
  loading.value = false;
  loadend.value = false;
  page.value = 1;
  dataList.value = [];
}
// 滚动加载
function getData() {
  if (loadend.value) return;
  if (loading.value) return;
  loading.value = true;
  loadTitle.value = `加载更多`;
  const params = {
    page: page.value,
    limit: limit.value,
    vehicle_id: checkCar.value.id,
    status: tabList[tab_current.value].id,
  };
  voucherList(params)
    .then((res: any) => {
      let list = res.data.list || [];
      loadend.value = list.length < limit.value;
      dataList.value = dataList.value.concat(list);
      loading.value = false;
      loadTitle.value = loadend.value ? `没有更多内容啦~` : `加载更多`;
      page.value++;
    })
    .catch(() => {
      loading.value = false;
      loadTitle.value = `加载更多`;
    });
}
onReachBottom(() => {
  getData();
});

// 控制吸顶内容的背景色
const isMove = ref(false);
onPageScroll((e) => {
  if (e.scrollTop > 0.5) {
    isMove.value = true;
  } else {
    isMove.value = false;
  }
});

// 定义Tab项的类型
interface TabItem {
  name: string;
  id: number;
}
// 创建tabs响应式数据
const tabList = reactive<TabItem[]>([
  { name: "待使用", id: 1 },
  { name: "已核销", id: 2 },
  { name: "已失效", id: 0 },
]);
let tab_current = ref(0);
// 定义方法
function changeTab(item: TabItem, index: number) {
  tab_current.value = index;
  clearData();
  getData();
  console.log("item", item.id);
}
</script>

<style scoped lang="scss">
.container {
  padding-bottom: calc(
    50rpx + constant(safe-area-inset-bottom)
  ); ///兼容 IOS<11.2/
  padding-bottom: calc(50rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

  .tab_box {
    background: #fff;
  }
  .car_class {
    width: 624rpx;
    margin: 0 auto;
    padding: 35rpx 30rpx;
    background: var(--view-card-linear);
    border-radius: 20rpx;
    border: 2rpx solid #fff;
    box-shadow: 0 4rpx 10rpx 0 rgba(118, 219, 229, 0.2);

    .car_item {
      &:not(:last-child) {
        margin-bottom: 30rpx;
      }
    }

    .car_info {
      flex-grow: 1;
      width: 468rpx;
      .car_top {
        .car_id {
          font-size: 34rpx;
          color: #284968;
          margin-bottom: 10rpx;
          font-weight: bold;
        }

        .car_name {
          font-size: 28rpx;
          color: #5d7e85;
        }
      }
    }

    .icon_box {
      flex-shrink: 0;
      width: 73rpx;
      height: 73rpx;
      margin-right: 20rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.list_box {
  padding: 0 30rpx;

  .list_item {
    background: #fff;
    border-radius: 16rpx;
    width: 690rpx;
    margin-bottom: 20rpx;

    .btm {
      padding: 0 30rpx;
      width: 100%;
      height: 88rpx;
      font-size: 28rpx;
      border-top: 2rpx solid #f9f7f7;

      .left_icon {
        color: #616161;

        .icon_box {
          width: 40rpx;
          height: 40rpx;
          margin-right: 20rpx;

          image {
            width: 100%;
            height: 100%;
          }
        }
      }

      .right_btn {
        border-radius: 99rpx;
        color: #fff;
        padding: 10rpx 30rpx;
        background: linear-gradient(270deg, #fbdb5a, #fe6c21);
      }

      .used {
        color: #fff;
        background: #616161;
      }
    }
  }
}

.car_box {
  padding: 20rpx 30rpx 40rpx;
  margin: 0 auto;
  width: 100%;

  .car_in_box {
    border: 2rpx solid #fff;
    border-radius: 20rpx;
    background: linear-gradient(270deg, #d6fdfc, #e6ffd7);
    padding: 24rpx 40rpx;
  }

  .left {
    font-size: 34rpx;
    color: #284968;
    font-weight: bold;

    .icon_box {
      width: 50rpx;
      height: 50rpx;
      margin-right: 20rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>